/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sniff;

import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import jpcap.JpcapCaptor;
import jpcap.NetworkInterface;
import jpcap.packet.*;
import jpcap.NetworkInterfaceAddress;
import jpcap.PacketReceiver;


/**
 *
 * @author DUYKIENBK
 */
public class sniff {
    


    /**
     * @param args the command line arguments
     */
    private static LogWindow lw;
    public static void main(String[] args) {
        // TODO code application logic here
        String[] a={"0"};
        try{
           // test();
            lw=new LogWindow();
            lw.setVisible(true);
        test2(a);
        }catch(Exception e){
            e.printStackTrace();
        }
        
    }
    
    public static void test(){
NetworkInterface[] devices = JpcapCaptor.getDeviceList();

//for each network interface
for (int i = 0; i < devices.length; i++) {
  //print out its name and description
  System.out.println(i+": "+devices[i].name + "(" + devices[i].description+")");

  //print out its datalink name and description
  System.out.println(" datalink: "+devices[i].datalink_name + "(" + devices[i].datalink_description+")");

  //print out its MAC address
  System.out.print(" MAC address:");
  for (byte b : devices[i].mac_address)
    System.out.print(Integer.toHexString(b&0xff) + ":");
  System.out.println();

  //print out its IP address, subnet mask and broadcast address
  for (NetworkInterfaceAddress a : devices[i].addresses)
    System.out.println(" address:"+a.address + " " + a.subnet + " "+ a.broadcast);
}

try{

JpcapCaptor captor=JpcapCaptor.openDevice(devices[0], 65535, false, 50000);

//call processPacket() to let Jpcap call PacketPrinter.receivePacket() for every packet capture.
//captor.processPacket(100,new PacketPrinter());

captor.setFilter("(dst host 192.168.1.10) and (dst port 51955)", true);

//captor.
//System.out.println(captor.received_packets);
System.out.println(captor.getPacket().data.toString());

//captor.processPacket(100,new PacketPrinter());
System.out.println(captor.received_packets);
//captor.
captor.close();
}catch(Exception e)
{
    e.printStackTrace();
}



        
    }
    
  public static void test2(String[] args) throws Exception {
      NetworkInterface[] devices = JpcapCaptor.getDeviceList();
		if(args.length<1){
			System.out.println("usage: java Tcpdump <select a number from the following>");
			
			for (int i = 0; i < devices.length; i++) {
				System.out.println(i+" :"+devices[i].name + "(" + devices[i].description+")");
				System.out.println("    data link:"+devices[i].datalink_name + "("
						+ devices[i].datalink_description+")");
				System.out.print("    MAC address:");
				for (byte b : devices[i].mac_address)
					System.out.print(Integer.toHexString(b&0xff) + ":");
				System.out.println();
				for (NetworkInterfaceAddress a : devices[i].addresses)
					System.out.println("    address:"+a.address + " " + a.subnet + " "
							+ a.broadcast);
			}
		}else{
			JpcapCaptor jpcap = JpcapCaptor.openDevice(devices[Integer.parseInt(args[0])], 20000, false, 20);
                        jpcap.setFilter("(dst host 192.168.1.250) and (dst port 6894)", true);
			jpcap.loopPacket(-1, new PacketProcess(){
                            @Override
                            public void receivePacket(Packet packet){
                                        String noidung="";
                                        //System.out.println(Stringbetween(packet.toString(),"192.168.112.","->/"));
                                        byte[] b = packet.data;
                                      
                                        if(b.length<17)
                                            return;
                                        
                                       
                                    //    if(b[3]==98)
                                    //        return;
                                        if(!"16".equals(Integer.toHexString(b[7] & 0xFF))) // byte 7 =16 la goi chat
                                            return;
                                        String may=tenmay(packet);
                                        //System.out.println(may);
                                        byte [] a = new byte[b.length-16];
                                        
                                        try{
                                       //      for(int i=0;i<17;i++){
                                            // System.out.println(b[i]);

                                         //   }
                                            
                                            for(int i=0;i<a.length;i++){
                                                a[i] = b[i+16];
                                            }

                                            noidung = new String (a,"UTF-8");
        
                                           // System.out.println(noidung);
                                        }catch(Exception e){
                                            e.printStackTrace();
                                        }
                                    
                                         addrow(may,noidung);
                                          playsound();
                                        
                                        
                            }
                            public String tenmay (Packet packet){
                                        //System.out.println(packet.header.toString());
                                        //System.out.println(packet.toString());
                                        return Stringbetween(packet.toString(),"192.168.1.","->/");
                                       
                            }
                            public String Stringbetween(String s1, String s2, String s3){
                                  try{
                                        int b = s1.indexOf(s2);
                                        int e = s1.indexOf(s3, b);
                                        String s ;
                                        int c= Integer.parseInt(s1.substring(b+s2.length(), e));
                                        c=c-100;
                                        s = String.valueOf(c);
                                        return(s);
                                  }catch(Exception e){
                                        return("");
                                  }
                           }

                            public void addrow(String may, String noidung) {
                                // this machine is client
                                  try {
                                      lw.addrow(may,noidung);
                                  }
                                  catch(Exception e) {
                                     e.printStackTrace();
                                  }
                            }  
                            
                        });
		}

  }
       public static void playsound() {
              try {
         // Open an audio input stream.
         File sound = new File(System.getProperty("user.dir")+"\\sound.wav");
         AudioInputStream audioIn = AudioSystem.getAudioInputStream(sound);
         // Get a sound clip resource.
         Clip clip = AudioSystem.getClip();
         // Open audio clip and load samples from the audio input stream.
         clip.open(audioIn);
         clip.start();
      } catch (UnsupportedAudioFileException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (LineUnavailableException e) {
         e.printStackTrace();
      }
   
    }   
    
}
class PacketProcess implements PacketReceiver {
  //this method is called every time Jpcap captures a packet
    @Override
  public void receivePacket(Packet packet) {
    //just print out a captured packet
    //System.out.println(packet);
  }
}


